{
 "cells": [
  {
   "cell_type": "raw",
   "id": "0967be84-ecc6-4206-b4e3-4b99196ce25c",
   "metadata": {},
   "source": [
    "from androguard.misc import AnalyzeAPK\n",
    "from collections import defaultdict\n",
    "# coding=utf-8\n",
    "import csv\n",
    "import os\n",
    "import networkx as nx\n",
    "import re"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ace69e0b-aedb-4bdd-b43e-0468811f53d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "def write_csv(opcode, f, id):  # 写csv\n",
    "    csv_write = csv.writer(f)\n",
    "    data_row = [id]\n",
    "    for op in opcode.keys():\n",
    "        data_row.append(opcode[op])\n",
    "    csv_write.writerow(data_row)\n",
    "\n",
    "def create_csv(smali_opcode, path):  # 创建csv\n",
    "    f = open(path, 'w+', newline='')\n",
    "    csv_write = csv.writer(f)\n",
    "    csv_head = ['id'] + smali_opcode\n",
    "    csv_write.writerow(csv_head)\n",
    "    return f\n",
    "\n",
    "def get_from_csv_gml(filename):  # 从API.csv获取每个API对应的权限mapping\n",
    "    per_value = {}\n",
    "    with open(filename, \"r\") as csvFile:\n",
    "        reader = csv.reader(csvFile)\n",
    "        for item in reader:\n",
    "            if reader.line_num == 1:\n",
    "                continue\n",
    "            name = item[0]\n",
    "            per = item[1]\n",
    "            # value[name] = functionname\n",
    "            if name not in per_value.keys():\n",
    "                per_value[name] = [per]\n",
    "            else:\n",
    "                per_value[name].append(per)\n",
    "    return per_value\n",
    "\n",
    "def get_external(nodeid, G):\n",
    "    return G.nodes[nodeid]['external']\n",
    "\n",
    "def n_neighbor(node, graph, hop=1):  # 节点的一跳邻居\n",
    "    ego_graph = nx.ego_graph(graph, node, radius=hop, undirected=True)\n",
    "    nodes = ego_graph.nodes\n",
    "    return nodes\n",
    "\n",
    "def get_label(node_id, G):\n",
    "    return G.nodes[node_id]['label']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "2afcec38-89d7-457d-8279-ee2f6d64e06e",
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_permission(path):\n",
    "    filename = path\n",
    "    permission = {}\n",
    "    with open(filename) as f:\n",
    "        content = f.readline().strip('\\n')\n",
    "        while content:\n",
    "            cons = content.split(' ')\n",
    "            if cons[0] not in permission:\n",
    "                permission[cons[0]] = set()\n",
    "            permission[cons[0]].add((cons[1], 'Permission:' + cons[2]))\n",
    "            content = f.readline().strip('\\n')\n",
    "    return permission\n",
    "\n",
    "def df_from_G(G):\n",
    "    import pandas as pd\n",
    "    df = pd.DataFrame(G.nodes(data=True))\n",
    "    try:\n",
    "        attr = df[1].apply(pd.Series)\n",
    "    except KeyError:\n",
    "        return False\n",
    "    node_attr = pd.concat([df[0], attr], axis=1)\n",
    "    node_attr = node_attr.rename(columns={0: 'id'})\n",
    "    return node_attr\n",
    "\n",
    "def node2function(s):  # 根据节点名称获取函数名称\n",
    "    first = s.find(' ')\n",
    "    s = s[first + 1:]\n",
    "    if s.find('@ ') < 0:\n",
    "        first = s.rfind('>')\n",
    "        s = s[:first]\n",
    "    else:\n",
    "        first = s.find('[access_flags')\n",
    "        s = s[:first - 1]\n",
    "    return s\n",
    "\n",
    "def getMethod2NodeMap(G):\n",
    "    method2nodeMap = {}\n",
    "    try:\n",
    "        node_attr = df_from_G(G)\n",
    "        labels = node_attr.label\n",
    "        ids = node_attr.id\n",
    "    except Exception:\n",
    "        return method2nodeMap\n",
    "    i = 0\n",
    "    pattern = re.compile(r'&#(.+?);')\n",
    "    while i < len(ids):\n",
    "        nodeid = ids.get(i)\n",
    "        label = labels.get(i)\n",
    "        function = node2function(label)\n",
    "        rt = pattern.findall(function)\n",
    "        for r in rt:\n",
    "            function.replace(\"&#%s;\"%r, chr(int(r)))\n",
    "        method = function.replace(\";->\", \"; \").replace(\"(\", \" (\")\n",
    "        method2nodeMap.update({method: (nodeid, function)})\n",
    "        i = i + 1\n",
    "    return method2nodeMap\n",
    "\n",
    "def get_smaliOpcode(filename):  # read all smali opcode list\n",
    "        opcode = list()\n",
    "        with open(filename, 'r') as fileObject:\n",
    "            lines = fileObject.readlines()\n",
    "        for line in lines:\n",
    "            opcode.append(line.rstrip('\\n'))\n",
    "        return opcode\n",
    "\n",
    "\"\"\"----------------------------------------------PERMISSOIN METHOD-------------------------------------------------------------\"\"\"\n",
    "def is_in_funcList(funcList, t):  # 节点是否再函数列表中\n",
    "    for f in funcList:\n",
    "        # 假如在，就是true\n",
    "        if t.find(f) >= 0:\n",
    "            return True\n",
    "    return False\n",
    "\n",
    "def get_nodeid_label(G, function):  # 通过方法（类+函数） 获取id和label\n",
    "    if type(function) == int:\n",
    "        return function, G.nodes[function]['label']\n",
    "    nodes = G.nodes\n",
    "    for node in nodes:\n",
    "        label = G.nodes[node]['label']\n",
    "        if label.find(function) >= 0:\n",
    "            return node, label\n",
    "    return \"\", \"\"\n",
    "\n",
    "def getclass(functionname):\n",
    "    index = functionname.find(';->')\n",
    "    return functionname[len('<analysis.MethodAnalysis L'):index]\n",
    "\n",
    "# 将方法(外部) 映射为  原来的名称: 父类名称 ,  id\n",
    "def get_mappings(function, classname):\n",
    "    # 传入方法和类名。\n",
    "    mappings = {}\n",
    "    nodeid, nodelabel = get_nodeid_label(G, function)\n",
    "    #  id + label\n",
    "    if nodeid == \"\":\n",
    "        return mappings\n",
    "    classname = 'L' + classname.replace('<analysis.MethodAnalysis ', '') + ';'\n",
    "    funcList = []\n",
    "    try:\n",
    "        # 获得某个类所有的方法\n",
    "        tmp = class_functions[classname]\n",
    "\n",
    "        for t in tmp:\n",
    "            # 获得每个方法的全程 funcList\n",
    "            funcList.append(method2nodeMap[t][1])\n",
    "    except KeyError:\n",
    "        funcList = []\n",
    "    \n",
    "    # funcList 某个c中，全部的方法名称 ['Lcom/qihoo/util/Configuration; <clinit> ()V', 'Lcom/qihoo/util/Configuration; <init> ()V']\n",
    "    t_id = nodeid\n",
    "    t = nodelabel\n",
    "    # 判断传入的类是否为外部类。\n",
    "    external = get_external(nodeid, G)\n",
    "    # 假如是external(不重要吧。)\n",
    "    if external == 1:\n",
    "        t_class = classname\n",
    "        # 假如不在则执行\n",
    "        if not is_in_funcList(funcList, t):  # t is in super class or system function\n",
    "            if t_class in super_dic.keys():\n",
    "                super_class = super_dic[t_class]\n",
    "                while True:\n",
    "                    new_label = t.replace(t_class, super_class)\n",
    "                    try:\n",
    "                        super_funcList = class_functions[super_class]\n",
    "                        if is_in_funcList(super_funcList, new_label):\n",
    "                            mappings[t] = (new_label, t_id)\n",
    "                            break\n",
    "                        else:\n",
    "                            t_class = super_class\n",
    "                            super_class = super_dic[t_class]\n",
    "                    except KeyError:\n",
    "                        mappings[t] = (new_label, t_id)\n",
    "                        break\n",
    "    return mappings\n",
    "    \n",
    "def substitude():  # 替换成子类\n",
    "    functions = node_attr.label\n",
    "    ids = node_attr.id\n",
    "\n",
    "    # start method connect run method\n",
    "    for c in class_functions:\n",
    "        if c in implement_dic:\n",
    "            super_c = implement_dic[c]\n",
    "        else:\n",
    "            super_c = \"\"\n",
    "        # 如果在这个replacemap中。\n",
    "        if super_c in replacemap:\n",
    "            index = 0 \n",
    "            while index < len(ids):\n",
    "                func = functions.get(index)\n",
    "                # 寻找有没有<init> 方法\n",
    "                if func.find(c + \"-><init>(L\") >= 0:\n",
    "                    left = func.find(\";-><init>(L\") + len(\";-><init>(L\")\n",
    "                    right = func.find(\";\", left)\n",
    "                    baseclass = func[left: right]\n",
    "\n",
    "                    #  android/content/Context\n",
    "                    index2 = 0\n",
    "\n",
    "                    # run\n",
    "                    func_list = replacemap[super_c]\n",
    "                    while index2 < len(ids):\n",
    "                        func_tmp = functions.get(index2)\n",
    "                        for ftmp in func_list:\n",
    "                            if func_tmp.find(c + \"->\" + ftmp) >= 0:\n",
    "                                class2runinit[baseclass].update({ids.get(index2): super_c[1:-1]})\n",
    "                        index2 = index2 + 1\n",
    "                    break\n",
    "                index = index + 1\n",
    "    \n",
    "    # print(class2runinit)   {'android/content/Context': {4: 'java/lang/Runnable'}})\n",
    "    mappings = {}\n",
    "    index = 0\n",
    "    # 将外部类（名字可能是内部类的方法）映射成  内部类+函数： 外部内+函数  ， 编号ID\n",
    "    #  Lcom/qihoo/util/StubApp1520421995;->getApplicationContext()Landroid/content/Context;>': ('<analysis.MethodAnalysis Landroid/app/Application;->getApplicationContext()Landroid/content/Context;>', 59)\n",
    "    while index < len(ids):\n",
    "        # 获取 当前index 的 类；->方法 。\n",
    "        label = functions.get(index)\n",
    "        # 获取 当前index 的 类名 com/qihoo/util/StubApplication\n",
    "        classname = getclass(label)\n",
    "        mappings.update(get_mappings(label, classname))\n",
    "        index = index + 1\n",
    "    # 将外部类（名字可能是内部类的方法）映射成  内部类+函数： 外部内+函数  ， 编号ID\n",
    "    class_functions_copy = class_functions.copy()\n",
    "    for classname in class_functions_copy:\n",
    "        for function in class_functions_copy[classname]:\n",
    "            label = method2nodeMap[function][1]\n",
    "            mappings.update(get_mappings(label, classname))\n",
    "    # print(mappings)\n",
    "    # print(super_dic)\n",
    "    res = {}\n",
    "    for function in mappings:\n",
    "        super_function = mappings[function][0]\n",
    "        for func in per_map:\n",
    "            if super_function.find(func) >= 0:\n",
    "                res[mappings[function][1]] = []\n",
    "                for p in per_map[func]:\n",
    "                    res[mappings[function][1]].append(p)\n",
    "    return res  # 所有被替换成子类的敏感API\n",
    "\n",
    "\n",
    "def deal_node(nodeid):\n",
    "    permission_node = {}\n",
    "    # 获取其后继节点。\n",
    "    targets = G.successors(nodeid)\n",
    "    for t in targets:\n",
    "        # 获取邻居的lable\n",
    "        label = get_label(t,G)\n",
    "        for k in method_dic.keys():\n",
    "            # k=lable\n",
    "            # 假如在邻居中发现method_dic.keys\n",
    "            if label.find(k) >= 0:\n",
    "                for ki in method_dic[k]:\n",
    "                    if ki not in permission_node:\n",
    "                        permission_node[ki] = set()\n",
    "                        # permission_node[W] = 1,2,3,4\n",
    "                        # permission_node[R] = 2,1230123,12315...\n",
    "                    permission_node[ki].add(nodeid)\n",
    "    return permission_node"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "e42b6400-cb1d-4c97-9884-258d9a45f5d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)\n",
    "query_method = \"Landroid/content/ContentResolver;->query(Landroid/net/Uri; [Ljava/lang/String; Ljava/lang/String; [Ljava/lang/String; Ljava/lang/String;)Landroid/database/Cursor;\"\n",
    "# Uri insert(Uri uri, ContentValues values)\n",
    "insert_method = \"Landroid/content/ContentResolver;->insert(Landroid/net/Uri; Landroid/content/ContentValues;)Landroid/net/Uri;\"\n",
    "# int delete(Uri uri, String selection, String[] selectionArgs)\n",
    "delete_method = \"Landroid/content/ContentResolver;->delete(Landroid/net/Uri; Ljava/lang/String; [Ljava/lang/String;)I\"\n",
    "# int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)\n",
    "update_method = \"Landroid/content/ContentResolver;->update(Landroid/net/Uri; Landroid/content/ContentValues; Ljava/lang/String; [Ljava/lang/String;)I\"\n",
    "\n",
    "method_dic = {query_method: ['R'], insert_method: ['W'], delete_method: ['W'], update_method: ['W', 'R']}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e2f316fb-1417-48e3-898c-17b39e1fc0a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "smali_opcode=get_smaliOpcode('/home/chenjiaxiong/jx_code/MsDroid-JXC/feature/Andro/Data/smaliOpcode.txt')\n",
    "cppermission = get_permission('/home/chenjiaxiong/jx_code/MsDroid-JXC/feature/Andro/Data/APIs/all_cp.txt')\n",
    "permission = []\n",
    "with open('/home/chenjiaxiong/jx_code/MsDroid-JXC/feature/Andro/Data/head.txt') as f:\n",
    "    permission = eval(f.read())\n",
    "opcodeFilename ='/home/chenjiaxiong/jx_code/android_sample/csv/opcode.csv'\n",
    "permissionFilename ='/home/chenjiaxiong/jx_code/android_sample/csv/permisson.csv'\n",
    "tplFilename = '/home/chenjiaxiong/jx_code/android_sample/csv/tpl.csv'\n",
    "CGfilename = '/home/chenjiaxiong/jx_code/android_sample/graph/98520bc4ea00c4566e46d533e2f263d0.gml'\n",
    "opcodeFile = create_csv(smali_opcode,opcodeFilename)\n",
    "replacemap = {'Landroid/os/AsyncTask;': ['onPreExecute', 'doInBackground'],\n",
    "              'Landroid/os/Handler;': ['handleMessage'], 'Ljava/lang/Runnable;': ['run']}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6f030e35-804c-4c0f-bae6-66dfabf2ed2b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "已经生成图啦.\n"
     ]
    }
   ],
   "source": [
    "apkfile = '/home/chenjiaxiong/jx_code/android_sample/apk/98520bc4ea00c4566e46d533e2f263d0.apk'  # APK 文件路径\n",
    "a, d, dx = AnalyzeAPK(apkfile)\n",
    "G = dx.get_call_graph()\n",
    "\n",
    "nx.write_gml(G, CGfilename, stringizer=str)  # save the call graph\n",
    "\n",
    "print('已经生成图啦.')\n",
    "G = nx.read_gml(CGfilename, label='id')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "439d283e-8a60-4b1b-90e9-46b9f73debda",
   "metadata": {},
   "source": [
    "----------------------START APK ANALYSIS----------------------"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "5bb6237a-d326-41d1-a02e-b4c76556220d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 每个class 有 几种方法.\n",
    "class_functions = defaultdict(list)  # mappings of class and its functions\n",
    "# class和他的父类class\n",
    "super_dic = {}  # mappings of class and its superclass(for class replacement)\n",
    "implement_dic = {}\n",
    "method2nodeMap = getMethod2NodeMap(G)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38f2baab-0ef4-42fb-922e-90d1715864ae",
   "metadata": {},
   "source": [
    "**<font color = red>Method2NodeMap</font>**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "940b4952-2ebc-47c8-9db5-85a772c69cd7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('LMTT/ThirdAppInfoNew; <init> ()V', (0, 'LMTT/ThirdAppInfoNew;-><init>()V'))\n",
      "('Ljava/lang/Object; <init> ()V', (1, 'Ljava/lang/Object;-><init>()V'))\n",
      "('Lcom/tencent/smtt/sdk/a/b; a (Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; I Z)V', (2, 'Lcom/tencent/smtt/sdk/a/b;->a(Landroid/content/Context; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; I Z)V'))\n",
      "('La/a$a; <init> ()V', (3, 'La/a$a;-><init>()V'))\n",
      "('La/a$a; <init> (La/a$1;)V', (4, 'La/a$a;-><init>(La/a$1;)V'))\n"
     ]
    }
   ],
   "source": [
    "for item in list(method2nodeMap.items())[:5]:\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e595df24-376c-4fbe-b606-628b3bd02d87",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "# 生成每个method + csv\n",
    "for classes in dx.get_classes():  # all class\n",
    "    class_name = str(classes.get_class().get_name())\n",
    "    \"\"\"\n",
    "    判断它的父类,假如不是 \"Ljava/lang/Object;\"\n",
    "        映射进 super_dic\n",
    "    \"\"\"\n",
    "    if classes.extends != \"Ljava/lang/Object;\":\n",
    "        super_dic[class_name] = str(classes.extends)\n",
    "        \"\"\"\n",
    "        假如他的父类在 replacemap当中，则 映射当前类 ————> 父类\n",
    "        \"\"\"\n",
    "        if str(classes.extends) in replacemap:\n",
    "            implement_dic[class_name] = str(classes.extends)\n",
    "\n",
    "    if classes.implements:\n",
    "        for imp in classes.implements:\n",
    "            if str(imp) in replacemap:\n",
    "                implement_dic[class_name] = str(imp)\n",
    "\n",
    "    for method in classes.get_methods():\n",
    "        if method.is_external():\n",
    "            continue\n",
    "        m = method.get_method()\n",
    "        class_functions[class_name].append(str(m.full_name))\n",
    "        c = defaultdict(int)\n",
    "        flag = False\n",
    "        for ins in m.get_instructions():  # count\n",
    "            flag = True  # exist instructions\n",
    "            c[ins.get_name()] += 1\n",
    "        opcode = {}\n",
    "        for p in smali_opcode:\n",
    "            opcode[p] = 0\n",
    "        for op in c:\n",
    "            if op in smali_opcode:\n",
    "                opcode[op] += c[op]\n",
    "        # 将操作码向量写进CSV当中\n",
    "        if flag:\n",
    "            try:\n",
    "                write_csv(opcode,opcodeFile, method2nodeMap[str(m.full_name)][0])\n",
    "            except Exception as e:\n",
    "                print(e)\n",
    "opcodeFile.close()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 166,
   "id": "be9e3a48-8219-441d-bf4e-8ed8fbafd2c0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "defaultdict(<class 'int'>, {'new-instance': 1, 'const-string': 1, 'invoke-direct': 1, 'iget': 1, 'invoke-virtual': 2, 'move-result-object': 2, 'return-object': 1})\n"
     ]
    }
   ],
   "source": [
    "print(c)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b75ac777-e9be-4c92-9f89-4b53b276a1c5",
   "metadata": {},
   "source": [
    "**<font color = red>super_dic</font>**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "3e08f346-d08b-44d7-87c5-c3bfc16c3b8b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('La/g;', 'Ljava/lang/RuntimeException;')\n",
      "('La/k;', 'Ljava/lang/RuntimeException;')\n",
      "('Landroid/net/http/DelegatingSSLSession$CertificateWrap;', 'Landroid/net/http/DelegatingSSLSession;')\n",
      "('Landroid/net/http/HttpResponseCache;', 'Ljava/net/ResponseCache;')\n",
      "('Landroid/net/http/HttpsConnection;', 'Landroid/net/http/Connection;')\n",
      "('Landroid/support/a/a/c$a;', 'Landroid/graphics/drawable/Drawable$ConstantState;')\n",
      "('Landroid/support/a/a/c$b;', 'Landroid/graphics/drawable/Drawable$ConstantState;')\n",
      "('Landroid/support/a/a/f;', 'Landroid/graphics/drawable/Drawable;')\n",
      "('Landroid/support/a/a/c;', 'Landroid/support/a/a/f;')\n",
      "('Landroid/support/a/a/g$a;', 'Landroid/support/a/a/g$d;')\n"
     ]
    }
   ],
   "source": [
    "for item in list(super_dic.items())[:10]:\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a385ad00-466f-40ce-b827-fc9a9e5ab02e",
   "metadata": {},
   "source": [
    "**<font color = red>implement_dic</font>**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "db77d15f-e680-4a94-9239-4699c8a3a657",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('La/h$2;', 'Ljava/lang/Runnable;')\n",
      "('La/h$3;', 'Ljava/lang/Runnable;')\n",
      "('Landroid/support/v4/app/a$1;', 'Ljava/lang/Runnable;')\n",
      "('Landroid/support/v4/app/m$1;', 'Ljava/lang/Runnable;')\n",
      "('Landroid/support/v4/app/n$1;', 'Landroid/os/Handler;')\n"
     ]
    }
   ],
   "source": [
    "for item in list(implement_dic.items())[:5]:\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "be794138-e30f-4a92-884e-fb32f599de29",
   "metadata": {},
   "outputs": [],
   "source": [
    "sensitiveapimap = {}\n",
    "class2runinit = defaultdict(dict)\n",
    "\n",
    "# 从API.csv获取每个API对应的权限mapping\n",
    "per_map = get_from_csv_gml('/home/chenjiaxiong/jx_code/MsDroid-JXC/feature/Andro/Data/APIs/API_all.csv')\n",
    "result_f = create_csv(permission, permissionFilename)\n",
    "node_attr = df_from_G(G)\n",
    "getresolver = \";->getContentResolver()Landroid/content/ContentResolver;\"\n",
    "functions = node_attr.label\n",
    "ids = node_attr.id"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "da9641ec-416e-4cea-8005-75f8335d287d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('Landroid/accounts/AbstractAccountAuthenticator$Transport;->addAccount(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String; Ljava/lang/String; Ljava/lang/String; Landroid/os/Bundle;)V', ['Permission:android.permission.ACCOUNT_MANAGER'])\n",
      "('Landroid/accounts/AbstractAccountAuthenticator$Transport;->confirmCredentials(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Landroid/os/Bundle;)V', ['Permission:android.permission.ACCOUNT_MANAGER'])\n",
      "('Landroid/accounts/AbstractAccountAuthenticator$Transport;->editProperties(Landroid/accounts/IAccountAuthenticatorResponse; Ljava/lang/String;)V', ['Permission:android.permission.ACCOUNT_MANAGER'])\n",
      "('Landroid/accounts/AbstractAccountAuthenticator$Transport;->getAccountRemovalAllowed(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account;)V', ['Permission:android.permission.ACCOUNT_MANAGER'])\n",
      "('Landroid/accounts/AbstractAccountAuthenticator$Transport;->getAuthToken(Landroid/accounts/IAccountAuthenticatorResponse; Landroid/accounts/Account; Ljava/lang/String; Landroid/os/Bundle;)V', ['Permission:android.permission.ACCOUNT_MANAGER'])\n"
     ]
    }
   ],
   "source": [
    "for item in list(per_map.items())[:5]:\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "f9ea278e-2beb-48ad-a910-3cbc03ede8e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "substitude_permission = substitude()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fba28bc3-6965-46cd-8211-69cb64103ff8",
   "metadata": {},
   "source": [
    "**<font color = red>subtitiude_permission</font>**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "d65e678c-1649-4c10-ab5b-b30b0f626677",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(29095, ['Permission:android.permission.RECEIVE_BOOT_COMPLETED', 'Permission:android.permission.ACCESS_NETWORK_STATE'])\n",
      "(29118, ['Permission:android.permission.RECEIVE_BOOT_COMPLETED', 'Permission:android.permission.ACCESS_NETWORK_STATE'])\n",
      "(29120, ['Permission:android.permission.RECEIVE_BOOT_COMPLETED', 'Permission:android.permission.ACCESS_NETWORK_STATE'])\n",
      "(39369, ['Permission:android.permission.RECEIVE_BOOT_COMPLETED', 'Permission:android.permission.ACCESS_NETWORK_STATE'])\n",
      "(39381, ['Permission:android.permission.RECEIVE_BOOT_COMPLETED', 'Permission:android.permission.ACCESS_NETWORK_STATE'])\n"
     ]
    }
   ],
   "source": [
    "for item in list(substitude_permission.items())[:5]:\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 164,
   "id": "0213f88b-cc74-42e9-9a5a-ea7962696f36",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<analysis.MethodAnalysis Lcom/beastbike/bluegogo/libcommon/jsbridge/BridgeWebView;->loadUrl(Ljava/lang/String;)V>\n",
      "这个是Lcom/beastbike/bluegogo/libcommon/jsbridge/BridgeWebView;的父类是：Landroid/webkit/WebView;\n",
      "Landroid/webkit/WebView;->loadUrl(Ljava/lang/String;)V>\n"
     ]
    }
   ],
   "source": [
    "label = labels.get(29095)\n",
    "print(label)\n",
    "print('这个是Lcom/beastbike/bluegogo/libcommon/jsbridge/BridgeWebView;的父类是：'+super_dic['Lcom/beastbike/bluegogo/libcommon/jsbridge/BridgeWebView;'])\n",
    "print('Landroid/webkit/WebView;->loadUrl(Ljava/lang/String;)V>')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b17e1812-bb29-40ee-b611-eb2df7d6fd35",
   "metadata": {},
   "source": [
    "substitude_permission子类所涉及的敏感api的,权限列表\n",
    "如 类A(自定义的) 他的父类为 B(系统自带) ---通过这种方法可以利用原本api_permission里面的映射\n",
    "则映射为 B :s\n",
    "start method connect run method \n",
    "class2runinitt\r\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 158,
   "id": "decf9c16-7f03-418b-9705-ac81f35a7dd5",
   "metadata": {},
   "outputs": [],
   "source": [
    "node_cp_permission = defaultdict(list)\n",
    "java_class = {}  # need to generate java file\n",
    "\n",
    "\"\"\"\n",
    "getContentResolver()Landroid/content/ContentResolver （敏感函数）\n",
    "java_clash 以;->getContentResolver()Landroid/content/ContentResolver;为中心节点\n",
    "研究其孩子节点所调用的permission,然后写入其中。\n",
    "\"\"\"\n",
    "\n",
    "# 看看他们调用了什么权限。（就是看其后继节点）\n",
    "for i in range(len(ids)):\n",
    "    function = functions.get(i)\n",
    "    if function.find(getresolver) >= 0:\n",
    "        node_id = ids.get(i)\n",
    "        # 获得当前节点的邻居\n",
    "        nodes = n_neighbor(node_id, G)\n",
    "        # 遍历邻居节点.\n",
    "        for node in nodes:\n",
    "            # 返回一个邻居的邻居的node_permission\n",
    "            # deal_node  ->  处理邻居的邻居\n",
    "            node_permission = deal_node(node)\n",
    "            if node_permission:\n",
    "                label = get_label(node, G)\n",
    "                left = label.find(' ')\n",
    "                right = label.find('->')\n",
    "                function_class = label[left + 1: right]\n",
    "                java_class.update({function_class: node_permission})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "920d584a-f44c-43c9-81dd-ed5fecae009c",
   "metadata": {},
   "source": [
    "看看class都调用了什么权限"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 159,
   "id": "ed9aa9b0-d8a2-4788-bd7b-1212beaccef7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('Lcom/sina/weibo/sdk/b;', {'R': {36509}})\n",
      "('Lcom/alipay/sdk/util/k;', {'R': {13481}})\n",
      "('Lcom/amap/api/a/fy;', {'R': {19512}})\n",
      "('Lcom/sina/weibo/sdk/net/c;', {'R': {41047}})\n",
      "('Landroid/support/v7/widget/bg;', {'R': {10984}})\n"
     ]
    }
   ],
   "source": [
    "for item in list(java_class.items())[:5]:\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 147,
   "id": "27b59ac7-bd18-4ea0-bf1e-94cff6901d7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "class_name = set ()\n",
    "# 制造反编译器。\n",
    "\n",
    "from androguard.decompiler.decompiler import DecompilerDAD\n",
    "for dex in d:\n",
    "    dex.set_decompiler(DecompilerDAD(dex, dx))\n",
    "    for method in dex.get_methods():\n",
    "        # 假如该方法的类设计到权限。\n",
    "        if str(method.get_class_name()) in java_class:\n",
    "            # 获得设计权限的类\n",
    "            current_class = dex.get_class(method.get_class_name())\n",
    "            # 获取该类的source （代码）\n",
    "            content = str(current_class.get_source())\n",
    "            # 返回其权限。（POP返回字典对应的内容。）\n",
    "            node_permission = java_class.pop(method.get_class_name())\n",
    "            # 假如有调用content的URL。 'content://ctspermissionwithsignaturepath/yes': {('R', 'Permission:com.android.cts.permissionWithSignature')}\n",
    "            if content.find('content://') >= 0:\n",
    "                 for per in cppermission.keys():\n",
    "                        if content.find(per) >= 0:\n",
    "                            pers = cppermission[per]\n",
    "                            for p in pers:\n",
    "                                if p[0] in node_permission:\n",
    "                                    for n_id in node_permission[p[0]]:\n",
    "                                        node_cp_permission[n_id].append(p[1])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 148,
   "id": "30c31eb8-281d-4698-abf9-6d456c49b9ed",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "defaultdict(<class 'list'>, {19512: ['Permission:android.permission.WRITE_APN_SETTINGS'], 41047: ['Permission:android.permission.WRITE_APN_SETTINGS']})\n"
     ]
    }
   ],
   "source": [
    "print(node_cp_permission)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "id": "15b00351-49fc-4633-970e-cab0a5488cb3",
   "metadata": {},
   "outputs": [],
   "source": [
    "def count_permission(name, per_map):\n",
    "        result = {}\n",
    "        if name in per_map.keys():\n",
    "            for p in permission:\n",
    "                result[p] = 0\n",
    "            pers = per_map[name]\n",
    "            for per in pers:\n",
    "                if per not in result.keys():\n",
    "                    continue\n",
    "                result[per] = 1\n",
    "        return result\n",
    "result_f = create_csv(permission, permissionFilename)\n",
    "i = 0\n",
    "while i < len(ids):\n",
    "    s = functions.get(i)\n",
    "    s = node2function(s)\n",
    "    p = count_permission(s, per_map)\n",
    "    node_id = ids.get(i)\n",
    "    if node_id in node_cp_permission:  # 与content provider相关的权限\n",
    "        for per in permission:\n",
    "            p[per] = 0\n",
    "        for per in node_cp_permission[node_id]:\n",
    "            p[per] = 1\n",
    "    if node_id in substitude_permission:  # 子类是敏感的API\n",
    "        for per in permission:\n",
    "            p[per] = 0\n",
    "        for per in substitude_permission[node_id]:\n",
    "            p[per] = 1\n",
    "    if p != {}:\n",
    "        write_csv(p, result_f, node_id)\n",
    "        node_permission = []\n",
    "        for k in p:\n",
    "            if p[k] == 1:\n",
    "                node_permission.append(k)\n",
    "        sensitiveapimap.update({node_id: node_permission})\n",
    "    i += 1\n",
    "result_f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "id": "6a7c2e2d-038a-45e8-99d5-1b2b6caf5a02",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(264, ['Permission:android.permission.ACCESS_NETWORK_STATE', 'Permission:android.permission.RECEIVE_BOOT_COMPLETED'])\n",
      "(265, ['Permission:android.permission.ACCESS_NETWORK_STATE', 'Permission:android.permission.RECEIVE_BOOT_COMPLETED'])\n",
      "(266, ['Permission:android.permission.ACCESS_NETWORK_STATE', 'Permission:android.permission.RECEIVE_BOOT_COMPLETED'])\n",
      "(267, ['Permission:android.permission.ACCESS_NETWORK_STATE', 'Permission:android.permission.RECEIVE_BOOT_COMPLETED'])\n",
      "(268, ['Permission:android.permission.ACCESS_NETWORK_STATE', 'Permission:android.permission.RECEIVE_BOOT_COMPLETED'])\n"
     ]
    }
   ],
   "source": [
    "for item in list(sensitiveapimap.items())[:5]:\n",
    "    print(item)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "id": "d8fd1d58-a21b-4f08-a5d1-466949e00dd7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "defaultdict(<class 'dict'>, {'a/c': {45: 'java/lang/Runnable', 46: 'java/lang/Runnable'}, 'android/support/v4/app/m': {2329: 'java/lang/Runnable', 2909: 'java/lang/Runnable'}, 'android/support/v4/app/n': {2622: 'android/os/Handler'}, 'android/support/v4/app/s': {2772: 'java/lang/Runnable'}, 'android/support/v4/app/s$a': {2787: 'java/lang/Runnable'}, 'java/util/ArrayList': {2901: 'java/lang/Runnable', 2972: 'java/lang/Runnable', 2985: 'java/lang/Runnable'}, 'java/lang/Object': {2904: 'java/lang/Runnable'}, 'android/support/v4/f/a': {2913: 'java/lang/Runnable'}, 'android/support/v4/b/e': {3066: 'android/os/Handler'}, 'android/support/v4/view/ViewPager': {3852: 'java/lang/Runnable'}, 'android/support/v4/view/av$a': {5313: 'java/lang/Runnable'}, 'android/support/v4/widget/DrawerLayout$i': {5798: 'java/lang/Runnable'}, 'android/support/v4/widget/a': {5072: 'java/lang/Runnable'}, 'android/support/v4/widget/y': {6396: 'java/lang/Runnable'}, 'android/support/v7/app/AlertController': {6430: 'java/lang/Runnable', 6435: 'java/lang/Runnable'}, 'android/content/DialogInterface': {6490: 'android/os/Handler'}, 'android/support/v7/app/j': {6932: 'java/lang/Runnable', 5095: 'java/lang/Runnable'}, 'android/support/v7/view/menu/e$2': {7751: 'java/lang/Runnable'}, 'android/support/v7/widget/ActionBarOverlayLayout': {5153: 'java/lang/Runnable', 5148: 'java/lang/Runnable'}, 'android/support/v7/widget/RecyclerView': {9306: 'java/lang/Runnable', 9309: 'java/lang/Runnable', 3541: 'java/lang/Runnable'}, 'android/support/v7/widget/StaggeredGridLayoutManager': {9970: 'java/lang/Runnable'}, 'android/support/v7/widget/Toolbar': {10185: 'java/lang/Runnable'}, 'android/support/v7/widget/ak': {10486: 'java/lang/Runnable', 10488: 'java/lang/Runnable', 10490: 'java/lang/Runnable'}, 'android/support/v7/widget/ao': {10658: 'java/lang/Runnable', 7466: 'java/lang/Runnable'}, 'android/support/v7/widget/as': {10674: 'java/lang/Runnable', 10680: 'java/lang/Runnable', 5034: 'java/lang/Runnable'}, 'android/support/v7/widget/be': {10887: 'java/lang/Runnable'}, 'android/support/v7/widget/d': {7999: 'java/lang/Runnable'}, 'android/support/v7/widget/e': {11183: 'android/os/AsyncTask'}, 'b/a/c/a': {11525: 'android/os/Handler', 11614: 'java/lang/Runnable', 11671: 'java/lang/Runnable', 11546: 'android/os/Handler'}, 'com/a/a/a/a/a$c': {11746: 'java/lang/Runnable'}, 'com/alipay/apmobilesecuritysdk/face/APSecuritySdk': {12400: 'java/lang/Runnable'}, 'com/alipay/apmobilesecuritysdk/g/b': {12650: 'java/lang/Runnable'}, 'com/alipay/b/a/a/c/b': {12685: 'java/lang/Runnable'}, 'com/alipay/b/a/a/e/b': {12830: 'java/lang/Runnable'}, 'com/alipay/sdk/app/b': {12959: 'java/lang/Runnable', 12967: 'java/lang/Runnable'}, 'android/content/Context': {13017: 'java/lang/Runnable', 19339: 'java/lang/Runnable', 19760: 'java/lang/Runnable', 19766: 'java/lang/Runnable', 19723: 'java/lang/Runnable', 19935: 'java/lang/Runnable', 19932: 'java/lang/Runnable', 20282: 'java/lang/Runnable', 41061: 'android/os/AsyncTask', 41063: 'android/os/AsyncTask', 44983: 'java/lang/Runnable', 44976: 'java/lang/Runnable', 44999: 'java/lang/Runnable', 44998: 'java/lang/Runnable', 45000: 'java/lang/Runnable', 44978: 'java/lang/Runnable', 44975: 'java/lang/Runnable', 45027: 'java/lang/Runnable', 44985: 'java/lang/Runnable', 44691: 'java/lang/Runnable', 44835: 'java/lang/Runnable', 45028: 'java/lang/Runnable', 36566: 'java/lang/Runnable', 45029: 'java/lang/Runnable', 44876: 'java/lang/Runnable', 44980: 'java/lang/Runnable', 44979: 'java/lang/Runnable', 47397: 'java/lang/Runnable', 48494: 'java/lang/Runnable', 48491: 'java/lang/Runnable', 50893: 'java/lang/Runnable', 36341: 'java/lang/Runnable', 36545: 'java/lang/Runnable', 52515: 'java/lang/Runnable', 54435: 'java/lang/Runnable', 52362: 'java/lang/Runnable', 36333: 'java/lang/Runnable'}, 'com/alipay/sdk/auth/AuthActivity': {13098: 'java/lang/Runnable', 13096: 'java/lang/Runnable'}, 'com/alipay/sdk/auth/AuthActivity$b': {13129: 'java/lang/Runnable'}, 'android/app/Activity': {13042: 'java/lang/Runnable', 13508: 'java/lang/Runnable'}, 'com/alipay/sdk/authjs/c': {13171: 'java/lang/Runnable'}, 'com/alipay/sdk/data/a': {13188: 'java/lang/Runnable'}, 'com/alipay/sdk/widget/a': {13511: 'java/lang/Runnable', 13542: 'java/lang/Runnable'}, 'com/amap/api/a/a': {13588: 'android/os/Handler', 13614: 'android/os/Handler'}, 'com/amap/api/a/by$1': {15263: 'android/os/Handler'}, 'com/amap/api/a/by$c': {15514: 'java/lang/Runnable'}, 'com/amap/api/a/cd': {15631: 'android/os/Handler', 15683: 'android/os/Handler'}, 'com/amap/api/a/ct$1': {16181: 'java/lang/Runnable', 16188: 'java/lang/Runnable'}, 'com/amap/api/a/ct': {16180: 'java/lang/Runnable', 16215: 'java/lang/Runnable'}, 'com/amap/api/a/da': {16647: 'android/os/Handler'}, 'com/amap/api/a/db': {16990: 'android/os/Handler'}, 'com/amap/api/a/dc': {17178: 'android/os/Handler'}, 'com/amap/api/a/de': {17254: 'android/os/Handler'}, 'com/amap/api/a/dh': {17104: 'java/lang/Runnable', 17105: 'android/os/Handler'}, 'com/amap/api/a/ei': {17960: 'android/os/Handler'}, 'android/os/Looper': {18084: 'android/os/Handler', 20249: 'android/os/Handler', 26223: 'android/os/Handler', 26590: 'android/os/Handler', 40974: 'android/os/Handler', 43507: 'android/os/Handler', 43737: 'android/os/Handler', 46605: 'android/os/Handler', 46985: 'android/os/Handler', 47334: 'android/os/Handler', 47969: 'android/os/Handler', 50852: 'android/os/Handler', 50825: 'android/os/Handler', 50993: 'android/os/Handler', 51081: 'android/os/Handler'}, 'com/amap/api/a/fd': {18724: 'java/lang/Runnable'}, 'com/amap/api/a/fe': {18726: 'java/lang/Runnable'}, 'com/amap/api/a/fi': {18738: 'java/lang/Runnable', 18732: 'java/lang/Runnable'}, 'com/amap/api/a/fk': {18057: 'java/lang/Runnable'}, 'com/amap/api/a/fp': {18014: 'java/lang/Runnable'}, 'com/amap/api/a/gb': {19635: 'java/lang/Runnable'}, 'com/amap/api/a/gj': {19778: 'java/lang/Runnable'}, 'com/amap/api/a/hk': {20085: 'java/lang/Runnable'}, 'com/amap/api/a/ie': {19721: 'java/lang/Runnable'}, 'java/util/List': {19743: 'java/lang/Runnable', 53457: 'java/lang/Runnable'}, 'com/amap/api/a/jd': {20650: 'java/lang/Runnable'}, 'android/content/SharedPreferences$Editor': {20766: 'android/os/AsyncTask'}, 'com/amap/api/mapcore/b': {21353: 'java/lang/Runnable', 21358: 'java/lang/Runnable', 21361: 'java/lang/Runnable', 21383: 'java/lang/Runnable', 16336: 'java/lang/Runnable', 16158: 'java/lang/Runnable', 15437: 'java/lang/Runnable', 21414: 'java/lang/Runnable', 14831: 'java/lang/Runnable', 21423: 'java/lang/Runnable', 16249: 'java/lang/Runnable', 21428: 'java/lang/Runnable', 21430: 'java/lang/Runnable', 19837: 'java/lang/Runnable', 14147: 'android/os/Handler', 21468: 'java/lang/Runnable', 16262: 'java/lang/Runnable', 16245: 'java/lang/Runnable', 21472: 'java/lang/Runnable', 16076: 'java/lang/Runnable'}, 'com/amap/api/mapcore/b$1': {21369: 'java/lang/Runnable'}, 'com/amap/api/mapcore/b$14': {16362: 'java/lang/Runnable'}, 'com/amap/api/mapcore/b$18': {21391: 'java/lang/Runnable'}, 'com/amap/api/mapcore/b$3': {19857: 'java/lang/Runnable'}, 'com/amap/api/mapcore/i': {22052: 'java/lang/Runnable', 22056: 'java/lang/Runnable', 22059: 'java/lang/Runnable', 22061: 'java/lang/Runnable'}, 'com/amap/api/mapcore/j': {19812: 'java/lang/Runnable'}, 'com/amap/api/mapcore/offlinemap/a': {19826: 'java/lang/Runnable', 19817: 'java/lang/Runnable', 19866: 'java/lang/Runnable', 21068: 'android/os/Handler'}, 'com/amap/api/mapcore/q': {22592: 'java/lang/Runnable', 20848: 'java/lang/Runnable'}, 'com/amap/api/mapcore/w': {19838: 'android/os/Handler'}, 'com/amap/api/maps/offlinemap/OfflineMapManager$1': {13771: 'java/lang/Runnable', 22351: 'java/lang/Runnable', 22354: 'java/lang/Runnable', 23240: 'java/lang/Runnable'}, 'com/amap/api/maps/offlinemap/OfflineMapManager': {19823: 'java/lang/Runnable', 22423: 'java/lang/Runnable'}, 'com/amap/api/maps/utils/overlay/SmoothMoveMarker': {23311: 'java/lang/Runnable'}, 'com/amap/api/navi/AMapHudView': {19844: 'java/lang/Runnable'}, 'com/android/volley/CacheDispatcher': {25099: 'java/lang/Runnable'}, 'com/android/volley/ExecutorDelivery': {25142: 'java/lang/Runnable'}, 'com/android/volley/Request': {25176: 'java/lang/Runnable'}, 'com/android/volley/toolbox/ImageLoader': {25499: 'java/lang/Runnable'}, 'com/android/volley/toolbox/NetworkImageView$1': {25566: 'java/lang/Runnable'}, 'com/autonavi/amap/mapcore/BaseMapLoader': {25651: 'java/lang/Runnable'}, 'com/autonavi/amap/mapcore/MapCore': {20804: 'java/lang/Runnable'}, 'com/b/a/au': {26370: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/a/a': {27038: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/businessservice/authenticate/internal/BGUploadPassportActivity': {27816: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/libcommon/c/b/a': {3086: 'android/os/Handler'}, 'com/beastbike/bluegogo/libcommon/widget/pulltorefresh/e': {29520: 'java/lang/Runnable', 29505: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/main/a/d': {29860: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/main/a/e': {29894: 'java/lang/Runnable', 28580: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/main/activity/BGMainActivity': {28057: 'java/lang/Runnable', 30089: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/main/activity/BGMainActivity$7': {29818: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/changemobile/a/c': {30604: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/feedback/activity/BGFeedbackLockDetailActivity$2': {28745: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/feedback/b/a': {30907: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/order/activity/BGOrderListActivity$2$1': {29167: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/order/activity/BGOrderListActivity$2$2': {29158: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/wallet/activity/BGWalletCardDetailListActivity$2$1': {29184: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/wallet/activity/BGWalletCardDetailListActivity$2$2': {29185: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/wallet/activity/BGWalletDepositListActivity$2$1': {29164: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/wallet/activity/BGWalletDepositListActivity$2$2': {29175: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/wallet/activity/BGWalletTransactionListActivity$2$1': {29186: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/wallet/activity/BGWalletTransactionListActivity$2$2': {29177: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/wallet/activity/BGWalletVoucherListActivity$5$1': {29182: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/wallet/activity/BGWalletScoreActivity$b$1': {31792: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/module/user/wallet/b/f': {28640: 'java/lang/Runnable'}, 'com/beastbike/bluegogo/service/BGDownloadService': {29159: 'android/os/Handler'}, 'com/beastbike/bluegogo/widget/CircleProgress': {30279: 'android/os/Handler', 32288: 'java/lang/Runnable'}, 'com/facebook/b/b/e': {32883: 'java/lang/Runnable'}, 'com/facebook/c/a': {32933: 'java/lang/Runnable', 32939: 'java/lang/Runnable'}, 'com/facebook/common/b/b': {33093: 'java/lang/Runnable'}, 'com/facebook/drawee/b/a': {33806: 'java/lang/Runnable'}, 'android/graphics/drawable/Drawable': {34122: 'java/lang/Runnable'}, 'com/facebook/fresco/animation/a/c': {34553: 'java/lang/Runnable'}, 'com/facebook/fresco/animation/b/b/c': {33443: 'java/lang/Runnable'}, 'com/facebook/fresco/animation/c/a': {34651: 'java/lang/Runnable'}, 'com/facebook/imagepipeline/c/e': {34856: 'java/lang/Runnable'}, 'com/facebook/imagepipeline/c/q': {34951: 'java/lang/Runnable'}, 'com/facebook/imagepipeline/e/k': {35196: 'java/lang/Runnable'}, 'com/facebook/imagepipeline/l/ak$a': {33602: 'java/lang/Runnable'}, 'com/facebook/imagepipeline/l/av$a': {35817: 'java/lang/Runnable'}, 'com/facebook/imagepipeline/l/u': {35931: 'java/lang/Runnable'}, 'com/facebook/imagepipeline/l/v': {35938: 'java/lang/Runnable', 35941: 'java/lang/Runnable'}, 'com/google/zxing/client/android/a': {37942: 'java/lang/Runnable'}, 'com/google/zxing/client/android/e$a': {38055: 'java/lang/Runnable'}, 'com/journeyapps/barcodescanner/a/a$2': {38953: 'java/lang/Runnable'}, 'com/journeyapps/barcodescanner/a/b': {38969: 'java/lang/Runnable', 38973: 'java/lang/Runnable', 38976: 'java/lang/Runnable', 38980: 'java/lang/Runnable', 38985: 'java/lang/Runnable', 38989: 'java/lang/Runnable'}, 'com/journeyapps/barcodescanner/c$4': {38818: 'java/lang/Runnable'}, 'com/journeyapps/barcodescanner/d$1': {39092: 'java/lang/Runnable'}, 'com/journeyapps/barcodescanner/d': {39106: 'java/lang/Runnable', 39110: 'java/lang/Runnable'}, 'com/pingplusplus/android/PaymentActivity': {39166: 'android/os/Handler', 39175: 'java/lang/Runnable'}, 'com/pingplusplus/android/h': {39527: 'android/os/AsyncTask'}, 'com/qq/e/ads/banner/BannerView$1': {39608: 'java/lang/Runnable'}, 'com/qq/e/ads/banner/BannerView': {39607: 'java/lang/Runnable'}, 'com/qq/e/ads/contentad/ContentAD$1': {39691: 'java/lang/Runnable'}, 'com/qq/e/ads/contentad/ContentAD': {39690: 'java/lang/Runnable'}, 'com/qq/e/ads/interstitial/InterstitialAD$1': {39751: 'java/lang/Runnable'}, 'com/qq/e/ads/interstitial/InterstitialAD': {39750: 'java/lang/Runnable'}, 'com/qq/e/ads/nativ/NativeAD$1': {39800: 'java/lang/Runnable'}, 'com/qq/e/ads/nativ/NativeAD': {39799: 'java/lang/Runnable'}, 'com/qq/e/ads/nativ/NativeExpressAD$1': {39839: 'java/lang/Runnable'}, 'com/qq/e/ads/nativ/NativeExpressAD': {39838: 'java/lang/Runnable'}, 'com/qq/e/ads/nativ/NativeExpressADView$1': {39868: 'java/lang/Runnable'}, 'com/qq/e/ads/nativ/NativeExpressADView': {39867: 'java/lang/Runnable'}, 'com/qq/e/ads/nativ/NativeMediaAD$1': {39883: 'java/lang/Runnable'}, 'com/qq/e/ads/nativ/NativeMediaAD': {39882: 'java/lang/Runnable'}, 'com/qq/e/comm/services/RetCodeService': {40309: 'java/lang/Runnable'}, 'com/sina/weibo/sdk/b/b': {40604: 'android/os/Handler'}, 'com/sina/weibo/sdk/b/d': {40648: 'android/os/Handler'}, 'com/sina/weibo/sdk/b/g': {40659: 'java/lang/Runnable'}, 'com/sina/weibo/sdk/component/a/a': {40849: 'java/lang/Runnable'}, 'com/sina/weibo/sdk/d/j': {40944: 'java/lang/Runnable'}, 'com/sina/weibo/sdk/e/b': {40961: 'java/lang/Runnable', 40702: 'java/lang/Runnable'}, 'com/taobao/sophix/a/d': {41369: 'java/lang/Runnable'}, 'com/taobao/sophix/a/g': {41513: 'java/lang/Runnable', 41407: 'java/lang/Runnable', 41406: 'java/lang/Runnable', 41409: 'java/lang/Runnable'}, 'com/taobao/sophix/c/h$1': {41656: 'java/lang/Runnable'}, 'com/taobao/sophix/core/dex/a/b': {41753: 'java/lang/Runnable'}, 'com/tencent/mm/sdk/b/e$a': {41983: 'android/os/Handler'}, 'java/lang/Thread': {41979: 'java/lang/Runnable'}, 'com/tencent/mm/sdk/diffdev/a/b': {42032: 'java/lang/Runnable'}, 'java/lang/String': {42051: 'android/os/AsyncTask', 42024: 'android/os/AsyncTask', 44693: 'java/lang/Runnable', 44815: 'java/lang/Runnable', 44810: 'java/lang/Runnable', 44811: 'java/lang/Runnable', 44981: 'java/lang/Runnable', 44812: 'java/lang/Runnable', 44982: 'java/lang/Runnable', 48495: 'java/lang/Runnable', 36495: 'java/lang/Runnable', 36456: 'java/lang/Runnable'}, 'com/tencent/mm/sdk/openapi/WXApiImplV10$ActivityLifecycleCb': {42326: 'java/lang/Runnable', 42333: 'java/lang/Runnable'}, 'com/tencent/smtt/sdk/TbsLogReport': {43836: 'java/lang/Runnable'}, 'com/tencent/smtt/sdk/at': {36585: 'java/lang/Runnable'}, 'com/tencent/smtt/sdk/au': {44421: 'java/lang/Runnable'}, 'com/tencent/smtt/sdk/ax': {44425: 'java/lang/Runnable', 44426: 'java/lang/Runnable', 44428: 'java/lang/Runnable'}, 'com/tencent/smtt/sdk/bb': {43609: 'java/lang/Runnable'}, 'com/tencent/smtt/sdk/bd': {44153: 'java/lang/Runnable'}, 'com/tencent/smtt/sdk/WebView': {44138: 'java/lang/Runnable'}, 'com/tencent/smtt/sdk/i': {43192: 'java/lang/Runnable'}, 'com/tencent/smtt/sdk/SystemWebChromeClient': {44083: 'java/lang/Runnable'}, 'com/tencent/smtt/sdk/r': {44490: 'android/os/Handler'}, 'com/tencent/smtt/sdk/x': {44530: 'android/os/Handler'}, 'com/tencent/smtt/utils/TbsLogClient': {44577: 'java/lang/Runnable'}, 'com/tencent/smtt/utils/l': {36543: 'android/os/Handler'}, 'com/tencent/wxop/stat/StatAccount': {44696: 'java/lang/Runnable'}, 'com/tencent/wxop/stat/StatGameUser': {44917: 'java/lang/Runnable'}, 'com/tencent/wxop/stat/au': {45190: 'java/lang/Runnable', 45192: 'java/lang/Runnable', 45181: 'java/lang/Runnable', 45185: 'java/lang/Runnable', 45188: 'java/lang/Runnable', 45183: 'java/lang/Runnable'}, 'com/tencent/wxop/stat/b': {45144: 'java/lang/Runnable'}, 'com/tencent/wxop/stat/i': {45328: 'java/lang/Runnable'}, 'java/lang/Throwable': {44977: 'java/lang/Runnable', 50946: 'java/lang/Runnable'}, 'java/net/URI': {45571: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/aj': {45757: 'android/os/Handler'}, 'com/tendcloud/tenddata/aq': {45925: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/bc': {45566: 'java/lang/Runnable'}, 'java/net/InetSocketAddress': {45950: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/ag': {45677: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/dl': {46898: 'android/os/Handler'}, 'com/tendcloud/tenddata/ej': {47155: 'android/os/Handler', 36463: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/el': {47132: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/fb': {47262: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/fd': {36508: 'android/os/Handler', 46563: 'android/os/Handler'}, 'com/tendcloud/tenddata/fj': {47309: 'android/os/Handler'}, 'com/tendcloud/tenddata/fm': {46142: 'java/lang/Runnable', 45411: 'java/lang/Runnable', 45414: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/fq$a': {46964: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/fw': {46984: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/gj': {47451: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/zy': {47559: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/gv': {46586: 'java/lang/Runnable', 47457: 'java/lang/Runnable', 47435: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/hc': {36296: 'android/os/Handler'}, 'com/tendcloud/tenddata/hh': {47629: 'java/lang/Runnable', 47631: 'java/lang/Runnable', 47641: 'java/lang/Runnable', 47630: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/zz': {47293: 'java/lang/Runnable', 46919: 'java/lang/Runnable', 46917: 'java/lang/Runnable', 47941: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/b': {47949: 'java/lang/Runnable', 47950: 'java/lang/Runnable'}, 'android/view/View': {45872: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/w': {47985: 'java/lang/Runnable'}, 'com/tendcloud/tenddata/z': {45364: 'java/lang/Runnable'}, 'com/unionpay/mobile/android/hce/f': {48363: 'java/lang/Runnable'}, 'com/unionpay/mobile/android/pro/pboc/engine/b': {49371: 'java/lang/Runnable', 49369: 'java/lang/Runnable', 49373: 'java/lang/Runnable', 49370: 'java/lang/Runnable'}, 'com/unionpay/mobile/android/pro/views/x': {49691: 'java/lang/Runnable'}, 'com/unionpay/mobile/android/pro/views/a': {49744: 'java/lang/Runnable'}, 'com/unionpay/mobile/android/pro/views/k': {49873: 'java/lang/Runnable'}, 'com/unionpay/mobile/android/upwidget/UPRadiationView': {50084: 'android/os/Handler'}, 'com/unionpay/mobile/android/upwidget/UPScrollView': {48674: 'android/os/Handler'}, 'com/unionpay/WebViewJavascriptBridge': {48213: 'java/lang/Runnable', 52334: 'java/lang/Runnable'}, 'com/xiaomi/a/a/d/d$a': {52585: 'java/lang/Runnable'}, 'com/xiaomi/a/a/d/f': {52626: 'android/os/Handler', 52638: 'java/lang/Runnable'}, 'com/xiaomi/d/l': {52877: 'java/lang/Runnable'}, 'android/app/job/JobService': {52493: 'android/os/Handler'}, 'com/xiaomi/push/service/receivers/NetworkStatusReceiver': {55020: 'java/lang/Runnable'}, 'java/lang/ref/ReferenceQueue': {56516: 'java/lang/Runnable'}, 'org/eclipse/paho/a/a/a/a': {57213: 'java/lang/Runnable', 57244: 'java/lang/Runnable', 57382: 'java/lang/Runnable', 57383: 'java/lang/Runnable', 57573: 'java/lang/Runnable'}, 'java/io/InputStream': {57432: 'java/lang/Runnable'}, 'org/eclipse/paho/android/service/d': {58085: 'java/lang/Runnable'}})\n"
     ]
    }
   ],
   "source": [
    "print(class2runinit)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "id": "db00da6f-872c-4caf-9c69-8fa2a1981cf2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "\n",
    "# 将 LibRadar目录添加到 sys.path\n",
    "sys.path.append('/home/chenjiaxiong/jx_code/LibRadar')\n",
    "from literadar import LibRadarLite\n",
    "\n",
    "def get_pkg(apk_path, ratio=0.6):\n",
    "    lrd = LibRadarLite(apk_path)\n",
    "    pkgs = []\n",
    "    try:\n",
    "        res = lrd.compare()\n",
    "    except Exception:\n",
    "        return pkgs\n",
    "    for i in res:\n",
    "        p = i['Package']\n",
    "        try:\n",
    "            r = eval(i['Match Ratio'])\n",
    "            if r >= ratio:\n",
    "                pkgs.append(p)\n",
    "            r = '%f' % r\n",
    "        except KeyError:\n",
    "            r = 'Undefined'\n",
    "    return pkgs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "id": "10a39cec-3ec8-4d57-971f-8d5b1f8beaad",
   "metadata": {},
   "outputs": [],
   "source": [
    "TplSensitiveNodeMap = {}\n",
    "tpl_list = get_pkg(apkfile)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "id": "83b380a2-6ff4-4b75-830f-6c93eb9688a5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Lcom/alipay', 'Lcom/amap', 'Lcom/autonavi/aps/amapapi', 'Lcom/android/volley', 'Lcom/tendcloud/tenddata', 'Lcom/beastbike/bluegogo/libcommon/widget', 'Lcom/xiaomi/mipush/sdk', 'Lcom/xiaomi/f', 'Lcom/xiaomi/push', 'Lcom/google/c', 'Lcom/sina/weibo', 'Lcom/tencent/mm', 'Lcom/tencent/smtt', 'Lcom/tencent/wxop', 'Lcom/unionpay/mobile/android', 'Lcom/unionpay/tsmservice', 'Lorg/apache/http', 'Lorg/apache/commons', 'Lorg/json']\n"
     ]
    }
   ],
   "source": [
    "print(tpl_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "70667396-455b-46eb-a8bc-46ea99215d36",
   "metadata": {},
   "outputs": [],
   "source": [
    "labels = node_attr.label\n",
    "ids = node_attr.id\n",
    "i = 0\n",
    "leafsmap = {}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "id": "19b5cf96-a15d-43f4-ad06-c4fc8e800371",
   "metadata": {},
   "outputs": [],
   "source": [
    "replacemap = {'android/os/AsyncTask;->execute': (\n",
    "        'android/os/AsyncTask;->onPreExecute', 'android/os/AsyncTask;->doInBackground'),\n",
    "                           'android/os/Handler;->sendMessage': ('android/os/Handler;->handleMessage'),\n",
    "                           'java/lang/Thread;->start': ('java/lang/Runnable;->run')}\n",
    "def dfs(nodeid,deepth):\n",
    "        async_baseclass = {}\n",
    "        nodes = list()\n",
    "        leafs = set()\n",
    "        nodes.append(nodeid)\n",
    "        label = get_label(nodeid,G)\n",
    "        node_class = getclass(label)\n",
    "        # debug(node_class)\n",
    "        parent_class = getclass(label)\n",
    "        if node_class in class2runinit:\n",
    "            async_baseclass.update(class2runinit[node_class])\n",
    "        dp = 0\n",
    "        while nodes:\n",
    "            nodeid = nodes.pop()\n",
    "            label = get_label(nodeid, G)\n",
    "            for rk in replacemap:\n",
    "                if label.find(rk) >= 0:  # 调用了start函数\n",
    "                    for ck in class2runinit.keys():\n",
    "                        if parent_class.find(ck) >= 0:\n",
    "                            async_baseclass = class2runinit[ck]\n",
    "                            for asid in async_baseclass.keys():  # 查找对应的run函数\n",
    "                                funcs = replacemap[rk]\n",
    "                                for func in funcs:\n",
    "                                    if func.find(async_baseclass[asid]) >= 0:\n",
    "                                        nodes.append(asid)\n",
    "            leafs.add(nodeid)\n",
    "            targets = G.successors(nodeid)\n",
    "            if dp < deepth:\n",
    "                for t in targets:\n",
    "                    if t in leafs:\n",
    "                        continue\n",
    "                    nodes.append(t)\n",
    "            dp = dp + 1\n",
    "        return leafs\n",
    "\n",
    "def getTplSensitiveNode(nodeid):\n",
    "        TplSensitiveNodes = set()\n",
    "        leafs = dfs(nodeid,2)\n",
    "        for leaf in leafs:\n",
    "            if leaf in sensitiveapimap:\n",
    "                TplSensitiveNodes.add(leaf)\n",
    "        return TplSensitiveNodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "id": "d007e3e8-a2b5-41cd-82be-0bb5e2021c86",
   "metadata": {},
   "outputs": [],
   "source": [
    "while i < len(ids):\n",
    "            node_id = ids.get(i)\n",
    "            label = labels.get(i)\n",
    "            flag = False\n",
    "            node_class = \"L\" + getclass(label)\n",
    "            for tpl in tpl_list:\n",
    "                if node_class.find(tpl) >= 0:\n",
    "                    flag = True\n",
    "                    break\n",
    "            # 假如是第三方库。则...\n",
    "            if flag:\n",
    "                TplSensitiveNodeMap[node_id] = getTplSensitiveNode(node_id)\n",
    "            i = i + 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "id": "0b508e6b-386f-45d9-b50d-2029bf897ddf",
   "metadata": {},
   "outputs": [],
   "source": [
    "def writefile():\n",
    "    f = create_csv(permission, tplFilename)\n",
    "    for tplnode in TplSensitiveNodeMap:\n",
    "        sensitiveNodeList = TplSensitiveNodeMap[tplnode]\n",
    "        num_sensitive = len(sensitiveNodeList)\n",
    "        permap = {}\n",
    "        for p in permission:\n",
    "            permap[p] = 0\n",
    "        if num_sensitive != 0:\n",
    "            for sensitiveNode in sensitiveNodeList:\n",
    "                nodepers = sensitiveapimap[sensitiveNode]\n",
    "                for nodeper in nodepers:\n",
    "                    permap[nodeper] = permap[nodeper] + 1\n",
    "            for p in permission:\n",
    "                permap[p] = permap[p] / num_sensitive\n",
    "        write_csv(permap, f, tplnode)\n",
    "    f.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "id": "405ef252-f063-4bda-ad1f-8c650207340b",
   "metadata": {},
   "outputs": [],
   "source": [
    "writefile()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 157,
   "id": "9fd71a8f-9c27-4f5e-b83c-ea74e3e2820c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content://telephony/carriers\n",
      "package com.amap.api.a;\n",
      "public class fy {\n",
      "\n",
      "    private static String a()\n",
      "    {\n",
      "        try {\n",
      "            String v0_0 = android.net.Proxy.getDefaultHost();\n",
      "        } catch (String v0_1) {\n",
      "            com.amap.api.a.gg.a(v0_1, ProxyUtil, getDefHost);\n",
      "            v0_0 = 0;\n",
      "        }\n",
      "        if (v0_0 == null) {\n",
      "            v0_0 = null;\n",
      "        }\n",
      "        return v0_0;\n",
      "    }\n",
      "\n",
      "    public static String a(String p1)\n",
      "    {\n",
      "        return com.amap.api.a.gc.c(p1);\n",
      "    }\n",
      "\n",
      "    public static java.net.Proxy a(android.content.Context p4)\n",
      "    {\n",
      "        java.net.Proxy v0 = 0;\n",
      "        try {\n",
      "            if (android.os.Build$VERSION.SDK_INT < 11) {\n",
      "                v0 = com.amap.api.a.fy.b(p4);\n",
      "            } else {\n",
      "                v0 = com.amap.api.a.fy.a(p4, new java.net.URI(http://restapi.amap.com));\n",
      "            }\n",
      "        } catch (java.net.URI v1_1) {\n",
      "            com.amap.api.a.gg.a(v1_1, ProxyUtil, getProxy);\n",
      "        }\n",
      "        return v0;\n",
      "    }\n",
      "\n",
      "    private static java.net.Proxy a(android.content.Context p4, java.net.URI p5)\n",
      "    {\n",
      "        int v0_0;\n",
      "        if (!com.amap.api.a.fy.c(p4)) {\n",
      "            v0_0 = 0;\n",
      "        } else {\n",
      "            try {\n",
      "                int v0_5 = java.net.ProxySelector.getDefault().select(p5);\n",
      "            } catch (int v0_2) {\n",
      "                com.amap.api.a.gg.a(v0_2, ProxyUtil, getProxySelectorCfg);\n",
      "            }\n",
      "            if ((v0_5 == 0) || (v0_5.isEmpty())) {\n",
      "                v0_0 = 0;\n",
      "            } else {\n",
      "                v0_0 = ((java.net.Proxy) v0_5.get(0));\n",
      "                if ((v0_0 == 0) || (v0_0.type() == java.net.Proxy$Type.DIRECT)) {\n",
      "                    v0_0 = 0;\n",
      "                }\n",
      "            }\n",
      "        }\n",
      "        return v0_0;\n",
      "    }\n",
      "\n",
      "    private static boolean a(String p1, int p2)\n",
      "    {\n",
      "        if ((p1 == null) || ((p1.length() <= 0) || (p2 == -1))) {\n",
      "            int v0_2 = 0;\n",
      "        } else {\n",
      "            v0_2 = 1;\n",
      "        }\n",
      "        return v0_2;\n",
      "    }\n",
      "\n",
      "    private static int b()\n",
      "    {\n",
      "        try {\n",
      "            int v0 = android.net.Proxy.getDefaultPort();\n",
      "        } catch (Throwable v1) {\n",
      "            com.amap.api.a.gg.a(v1, ProxyUtil, getDefPort);\n",
      "        }\n",
      "        return v0;\n",
      "    }\n",
      "\n",
      "    private static java.net.Proxy b(android.content.Context p12)\n",
      "    {\n",
      "        Throwable v0_14;\n",
      "        int v10 = 0;\n",
      "        int v8 = -1;\n",
      "        if (!com.amap.api.a.fy.c(p12)) {\n",
      "            v0_14 = 0;\n",
      "        } else {\n",
      "            try {\n",
      "                String v3_0;\n",
      "                Throwable v2_8 = p12.getContentResolver().query(android.net.Uri.parse(content://telephony/carriers/preferapn), 0, 0, 0, 0);\n",
      "                try {\n",
      "                    if ((v2_8 == null) || (!v2_8.moveToFirst())) {\n",
      "                        v3_0 = 0;\n",
      "                    } else {\n",
      "                        Throwable v0_19 = v2_8.getString(v2_8.getColumnIndex(apn));\n",
      "                        if (v0_19 != null) {\n",
      "                            v0_19 = v0_19.toLowerCase(java.util.Locale.US);\n",
      "                        }\n",
      "                        if ((v0_19 == null) || (!v0_19.contains(ctwap))) {\n",
      "                            if ((v0_19 == null) || (!v0_19.contains(wap))) {\n",
      "                            } else {\n",
      "                                v3_0 = com.amap.api.a.fy.a();\n",
      "                                int v1_21 = com.amap.api.a.fy.b();\n",
      "                                try {\n",
      "                                    if ((android.text.TextUtils.isEmpty(v3_0)) || (v3_0.equals(null))) {\n",
      "                                        Throwable v0_25 = 0;\n",
      "                                        v3_0 = 0;\n",
      "                                    } else {\n",
      "                                        v0_25 = 1;\n",
      "                                    }\n",
      "                                } catch (Throwable v0_1) {\n",
      "                                    v3_0 = 0;\n",
      "                                    int v1_3 = v2_8;\n",
      "                                    Throwable v2_0 = v1_21;\n",
      "                                    try {\n",
      "                                        com.amap.api.a.gg.a(v0_1, ProxyUtil, getHostProxy);\n",
      "                                        Throwable v0_5 = com.amap.api.a.fv.o(p12);\n",
      "                                    } catch (Throwable v0_3) {\n",
      "                                        v2_8 = v1_3;\n",
      "                                        if (v2_8 != null) {\n",
      "                                            try {\n",
      "                                                v2_8.close();\n",
      "                                            } catch (int v1_12) {\n",
      "                                                com.amap.api.a.gg.a(v1_12, ProxyUtil, getHostProxy2);\n",
      "                                                com.google.a.a.a.a.a.a.a(v1_12);\n",
      "                                            }\n",
      "                                        }\n",
      "                                        throw v0_3;\n",
      "                                    }\n",
      "                                    if (v0_5 == null) {\n",
      "                                        v8 = v2_0;\n",
      "                                    } else {\n",
      "                                        boolean v4_2 = v0_5.toLowerCase(java.util.Locale.US);\n",
      "                                        Throwable v0_6 = com.amap.api.a.fy.a();\n",
      "                                        v2_0 = com.amap.api.a.fy.b();\n",
      "                                        if (v4_2.indexOf(ctwap) == -1) {\n",
      "                                            if (v4_2.indexOf(wap) == -1) {\n",
      "                                            } else {\n",
      "                                                if (android.text.TextUtils.isEmpty(v0_6)) {\n",
      "                                                    Throwable v2_7 = 0;\n",
      "                                                    v0_6 = v3_0;\n",
      "                                                } else {\n",
      "                                                    if (v0_6.equals(null)) {\n",
      "                                                    } else {\n",
      "                                                        v2_7 = 1;\n",
      "                                                    }\n",
      "                                                }\n",
      "                                                if (v2_7 == null) {\n",
      "                                                    v0_6 = com.amap.api.a.fy.a(QMTAuMC4wLjE3Mg==);\n",
      "                                                }\n",
      "                                                v8 = 80;\n",
      "                                                v3_0 = v0_6;\n",
      "                                            }\n",
      "                                        } else {\n",
      "                                            if (!android.text.TextUtils.isEmpty(v0_6)) {\n",
      "                                                if (!v0_6.equals(null)) {\n",
      "                                                    v10 = 1;\n",
      "                                                    v3_0 = v0_6;\n",
      "                                                }\n",
      "                                            }\n",
      "                                            if (v10 == 0) {\n",
      "                                                v3_0 = com.amap.api.a.fy.a(QMTAuMC4wLjIwMA==);\n",
      "                                            }\n",
      "                                            if (v2_0 != -1) {\n",
      "                                            } else {\n",
      "                                                v8 = 80;\n",
      "                                            }\n",
      "                                        }\n",
      "                                    }\n",
      "                                    if (v1_3 == 0) {\n",
      "                                        try {\n",
      "                                            if (!com.amap.api.a.fy.a(v3_0, v8)) {\n",
      "                                            } else {\n",
      "                                                v0_14 = new java.net.Proxy(java.net.Proxy$Type.HTTP, java.net.InetSocketAddress.createUnresolved(v3_0, v8));\n",
      "                                            }\n",
      "                                        } catch (Throwable v0_15) {\n",
      "                                            com.amap.api.a.gg.a(v0_15, ProxyUtil, getHostProxy2);\n",
      "                                            com.google.a.a.a.a.a.a.a(v0_15);\n",
      "                                        }\n",
      "                                        return v0_14;\n",
      "                                    } else {\n",
      "                                        try {\n",
      "                                            v1_3.close();\n",
      "                                        } catch (Throwable v0_9) {\n",
      "                                            com.amap.api.a.gg.a(v0_9, ProxyUtil, getHostProxy2);\n",
      "                                            com.google.a.a.a.a.a.a.a(v0_9);\n",
      "                                        }\n",
      "                                    }\n",
      "                                    if (v1_21 != -1) {\n",
      "                                        v8 = v1_21;\n",
      "                                    } else {\n",
      "                                        v8 = 80;\n",
      "                                    }\n",
      "                                } catch (Throwable v0_0) {\n",
      "                                    v8 = v1_21;\n",
      "                                    v3_0 = 0;\n",
      "                                    com.amap.api.a.gg.a(v0_0, ProxyUtil, getHostProxy1);\n",
      "                                    com.google.a.a.a.a.a.a.a(v0_0);\n",
      "                                    if (v2_8 == null) {\n",
      "                                    } else {\n",
      "                                        try {\n",
      "                                            v2_8.close();\n",
      "                                        } catch (Throwable v0_4) {\n",
      "                                            com.amap.api.a.gg.a(v0_4, ProxyUtil, getHostProxy2);\n",
      "                                            com.google.a.a.a.a.a.a.a(v0_4);\n",
      "                                        }\n",
      "                                    }\n",
      "                                }\n",
      "                                if (v0_25 == null) {\n",
      "                                    try {\n",
      "                                        v3_0 = com.amap.api.a.fy.a(QMTAuMC4wLjE3Mg==);\n",
      "                                    } catch (Throwable v0_1) {\n",
      "                                        v2_0 = v1_21;\n",
      "                                        v1_3 = v2_8;\n",
      "                                    } catch (Throwable v0_0) {\n",
      "                                        v8 = v1_21;\n",
      "                                    }\n",
      "                                }\n",
      "                            }\n",
      "                        } else {\n",
      "                            v3_0 = com.amap.api.a.fy.a();\n",
      "                            Throwable v0_10 = com.amap.api.a.fy.b();\n",
      "                            try {\n",
      "                                if ((android.text.TextUtils.isEmpty(v3_0)) || (v3_0.equals(null))) {\n",
      "                                    int v1_6 = 0;\n",
      "                                    v3_0 = 0;\n",
      "                                } else {\n",
      "                                    v1_6 = 1;\n",
      "                                }\n",
      "                            } catch (int v1_2) {\n",
      "                                v3_0 = 0;\n",
      "                                v2_0 = v0_10;\n",
      "                                v0_1 = v1_2;\n",
      "                                v1_3 = v2_8;\n",
      "                            } catch (int v1_1) {\n",
      "                                v8 = v0_10;\n",
      "                                v3_0 = 0;\n",
      "                                v0_0 = v1_1;\n",
      "                            }\n",
      "                            if (v1_6 == 0) {\n",
      "                                try {\n",
      "                                    v3_0 = com.amap.api.a.fy.a(QMTAuMC4wLjIwMA==);\n",
      "                                } catch (int v1_11) {\n",
      "                                    v1_3 = v2_8;\n",
      "                                    v2_0 = v0_10;\n",
      "                                    v0_1 = v1_11;\n",
      "                                } catch (int v1_8) {\n",
      "                                    v8 = v0_10;\n",
      "                                    v0_0 = v1_8;\n",
      "                                }\n",
      "                            }\n",
      "                            if (v0_10 == -1) {\n",
      "                                v0_10 = 80;\n",
      "                            }\n",
      "                            v8 = v0_10;\n",
      "                        }\n",
      "                    }\n",
      "                } catch (Throwable v0_1) {\n",
      "                    v1_3 = v2_8;\n",
      "                    v3_0 = 0;\n",
      "                    v2_0 = -1;\n",
      "                } catch (Throwable v0_0) {\n",
      "                    v3_0 = 0;\n",
      "                }\n",
      "                if (v2_8 == null) {\n",
      "                } else {\n",
      "                    try {\n",
      "                        v2_8.close();\n",
      "                    } catch (Throwable v0_11) {\n",
      "                        com.amap.api.a.gg.a(v0_11, ProxyUtil, getHostProxy2);\n",
      "                        com.google.a.a.a.a.a.a.a(v0_11);\n",
      "                    }\n",
      "                }\n",
      "            } catch (Throwable v0_1) {\n",
      "                v1_3 = 0;\n",
      "                v2_0 = -1;\n",
      "                v3_0 = 0;\n",
      "            } catch (Throwable v0_0) {\n",
      "                v2_8 = 0;\n",
      "                v3_0 = 0;\n",
      "            } catch (Throwable v0_3) {\n",
      "                v2_8 = 0;\n",
      "            } catch (Throwable v0_3) {\n",
      "            }\n",
      "        }\n",
      "        return v0_14;\n",
      "    }\n",
      "\n",
      "    private static boolean c(android.content.Context p1)\n",
      "    {\n",
      "        int v0_1;\n",
      "        if (com.amap.api.a.fv.m(p1) != 0) {\n",
      "            v0_1 = 0;\n",
      "        } else {\n",
      "            v0_1 = 1;\n",
      "        }\n",
      "        return v0_1;\n",
      "    }\n",
      "}\n",
      "\n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'debug' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[157], line 22\u001b[0m\n\u001b[1;32m     20\u001b[0m \u001b[38;5;28mprint\u001b[39m(per)\n\u001b[1;32m     21\u001b[0m \u001b[38;5;28mprint\u001b[39m(content)\n\u001b[0;32m---> 22\u001b[0m \u001b[43mdebug\u001b[49m\n\u001b[1;32m     23\u001b[0m pers \u001b[38;5;241m=\u001b[39m cppermission[per]\n\u001b[1;32m     24\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m p \u001b[38;5;129;01min\u001b[39;00m pers:\n",
      "\u001b[0;31mNameError\u001b[0m: name 'debug' is not defined"
     ]
    }
   ],
   "source": [
    "class_name = set ()\n",
    "# 制造反编译器。\n",
    "\n",
    "from androguard.decompiler.decompiler import DecompilerDAD\n",
    "for dex in d:\n",
    "    dex.set_decompiler(DecompilerDAD(dex, dx))\n",
    "    for method in dex.get_methods():\n",
    "        # 假如该方法的类设计到权限。\n",
    "        if str(method.get_class_name()) in java_class:\n",
    "            # 获得设计权限的类\n",
    "            current_class = dex.get_class(method.get_class_name())\n",
    "            # 获取该类的source （代码）\n",
    "            content = str(current_class.get_source())\n",
    "            # 返回其权限。（POP返回字典对应的内容。）\n",
    "            node_permission = java_class.pop(method.get_class_name())\n",
    "            # 假如有调用content的URL。 'content://ctspermissionwithsignaturepath/yes': {('R', 'Permission:com.android.cts.permissionWithSignature')}\n",
    "            if content.find('content://') >= 0:\n",
    "                 for per in cppermission.keys():\n",
    "                        if content.find(per) >= 0:\n",
    "                            print(per)\n",
    "                            print(content)\n",
    "                            debug\n",
    "                            pers = cppermission[per]\n",
    "                            for p in pers:\n",
    "                                if p[0] in node_permission:\n",
    "                                    for n_id in node_permission[p[0]]:\n",
    "                                        node_cp_permission[n_id].append(p[1])\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 156,
   "id": "1bb811d0-af44-4b61-8ca1-d7e4c9319bbf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "defaultdict(<class 'list'>, {19512: ['Permission:android.permission.WRITE_APN_SETTINGS', 'Permission:android.permission.WRITE_APN_SETTINGS', 'Permission:android.permission.WRITE_APN_SETTINGS', 'Permission:android.permission.WRITE_APN_SETTINGS', 'Permission:android.permission.WRITE_APN_SETTINGS', 'Permission:android.permission.WRITE_APN_SETTINGS', 'Permission:android.permission.WRITE_APN_SETTINGS', 'Permission:android.permission.WRITE_APN_SETTINGS'], 41047: ['Permission:android.permission.WRITE_APN_SETTINGS', 'Permission:android.permission.WRITE_APN_SETTINGS']})\n"
     ]
    }
   ],
   "source": [
    "print(node_cp_permission)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 165,
   "id": "9c304dd3-b3d7-4263-a7e9-ac7cd4949dd2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<analysis.MethodAnalysis Lcom/amap/api/a/fy;->b(Landroid/content/Context;)Ljava/net/Proxy; [access_flags=private static] @ 0x22fa08>\n"
     ]
    }
   ],
   "source": [
    "label = get_label(19512,G)\n",
    "print(label)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
